from django.http import HttpResponse
from django.shortcuts import render
from .models import Book

# 使用django封装好的connection对象，会自动读取settings.py中数据库的配置信息
from django.db import connection

# 演示原生版sql
def index(request):
    # 获取游标对象
    cursor = connection.cursor() # 只有这一句是pymysql的语法
    # 以下pymysql的语法
    # 拿到游标对象后执行sql语句
    cursor.execute("select * from book")
    # 获取所有的数据
    rows = cursor.fetchall()
    # 遍历查询到的数据
    for row in rows:
        print(row)
    return HttpResponse("查找成功！")

def add_book(request):
    book1 = Book(name="三国演义", author="罗贯中", price=100)
    book1.save()

    book2 = Book(name="水浒传", author="施耐庵", price=99)
    book2.save()
    return HttpResponse("添加成功！")

def query_book(request):
    books = Book.objects.all()
    for book in books:
        print(book.id, book.name, book.author, book.pub_time, book.price)

    return HttpResponse("查询成功！")

def filter_book(request):
    books = Book.objects.filter(name='三国演义')
    for book in books:
        print(book.id, book.name, book.author, book.pub_time, book.price)
    return HttpResponse("查询成功！")

def one_book(request):
    # books = Book.objects.get(name="三国演义11")
    try:
        books = Book.objects.get(name="三国演义11")
        print(books.name)

    except Book.DoesNotExist:
        print("图书不存在")
    return HttpResponse("查询成功！")

def sort_book(request):
    books = Book.objects.order_by('pub_time') # 升序
    books = Book.objects.order_by('-pub_time') # 降序
    for book in books:
        print(book.name)
    return HttpResponse("排序成功")

def modify_book(request):
    book = Book.objects.get(name="三国演义")
    book.name = "西游记"
    book.save()
    return HttpResponse("修改成功！")

def delete_book(request):
    book = Book.objects.get(name="水浒传")
    book.delete()
    return HttpResponse("删除成功！")